package org.dromara.comm_lhz.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.base.MPJBaseServiceImpl;
import org.dromara.comm_lhz.entity.AsCommodityDescribeImgEntity;
import org.dromara.comm_lhz.entity.AsCommodityEntity;
import org.dromara.comm_lhz.entity.AsCommodityImgEntity;
import org.dromara.comm_lhz.entity.SysUserEntity;
import org.dromara.comm_lhz.entity.dto.AsCommodityInfoDto;
import org.dromara.comm_lhz.entity.vo.AsCommodityInfoVo;
import org.dromara.comm_lhz.entity.vo.AsCommodityListVo;
import org.dromara.comm_lhz.mapper.AsCommodityHMapper;
import org.dromara.comm_lhz.mapper.SysUserHMapper;
import org.dromara.comm_lhz.service.AsCommodityDescribeImgHService;
import org.dromara.comm_lhz.service.AsCommodityHService;
import org.dromara.comm_lhz.service.AsCommodityImgHService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class AsCommodityHServiceImpl extends MPJBaseServiceImpl<AsCommodityHMapper, AsCommodityEntity> implements AsCommodityHService {

    @Autowired
    private AsCommodityHMapper asCommodityHMapper;
    @Autowired
    private AsCommodityImgHService asCommodityImgHService;
    @Autowired
    private AsCommodityDescribeImgHService asCommodityDescribeImgHService;
    @Autowired
    private SysUserHMapper sysUserMapper;


    @Override
    public Page<AsCommodityListVo> selCommodityList(Pageable pageable,Integer state) {
        // 创建用于查询的分页对象
        Page<AsCommodityEntity> entityPage = new Page<>(pageable.getPageNumber(), pageable.getPageSize());

        // 创建 QueryWrapper 来添加查询条件
        QueryWrapper<AsCommodityEntity> queryWrapper = new QueryWrapper<>();
        if (state != null) {
            queryWrapper.eq("state", state); // 添加 state 条件
        }

        // 查询数据库获取分页后的实体列表
        Page<AsCommodityEntity> asCommodityEntityPage = asCommodityHMapper.selectPage(entityPage, queryWrapper);

        // 创建用于返回的分页对象
        Page<AsCommodityListVo> asCommodityVoPage = new Page<>(pageable.getPageNumber(), pageable.getPageSize());

        // 将实体分页对象的属性复制到 VO 分页对象
        BeanUtil.copyProperties(asCommodityEntityPage, asCommodityVoPage);

        // 将 AsCommodityEntity 列表映射为 AsCommodityListVo 列表
        List<AsCommodityListVo> voList = asCommodityEntityPage.getRecords().stream()
            .map(entity -> {
                AsCommodityListVo vo = new AsCommodityListVo();
                BeanUtil.copyProperties(entity, vo);
                return vo;
            })
            .collect(Collectors.toList());

        // 将映射后的 VO 列表设置到 VO 分页对象中
        asCommodityVoPage.setRecords(voList);

        return asCommodityVoPage;
    }

    @Override
    @Transactional
    public void addCommodity(AsCommodityInfoDto asCommodityInfoDto) {
        //添加商品基本信息
        AsCommodityEntity asCommodityEntity = BeanUtil.copyProperties(asCommodityInfoDto, AsCommodityEntity.class);
        this.save(asCommodityEntity);
        //批量添加商品主图片
        Long id = asCommodityEntity.getId();

        List<String> imagePaths = asCommodityInfoDto.getImagePaths();
        List<AsCommodityImgEntity> asCommodityImgEntityList = imagePaths.stream()
            .map(imagePath -> {
                AsCommodityImgEntity asCommodityImgEntity = new AsCommodityImgEntity();
                asCommodityImgEntity.setCommodityId(id);
                asCommodityImgEntity.setUrl(imagePath);
                return asCommodityImgEntity;
            })
            .collect(Collectors.toList());
        asCommodityImgHService.saveBatch(asCommodityImgEntityList);

        //批量添加商品描述图片
        List<String> images = asCommodityInfoDto.getImages();
        List<AsCommodityDescribeImgEntity> asCommodityDescribeImgEntityList = images.stream().map(image -> {
            AsCommodityDescribeImgEntity asCommodityDescribeImgEntity = new AsCommodityDescribeImgEntity();
            asCommodityDescribeImgEntity.setCommodityId(id);
            asCommodityDescribeImgEntity.setDescribeImage(image);
            return asCommodityDescribeImgEntity;
        }).collect(Collectors.toList());
        asCommodityDescribeImgHService.saveBatch(asCommodityDescribeImgEntityList);

    }

    @Override
    @Transactional
    public void updateCommodity(AsCommodityInfoDto asCommodityInfoDto) {
        // 更新商品基本信息
        AsCommodityEntity asCommodityEntity = BeanUtil.copyProperties(asCommodityInfoDto, AsCommodityEntity.class);
        asCommodityHMapper.updateById(asCommodityEntity);

        if (Objects.nonNull(asCommodityInfoDto.getImagePaths())) {
            //删除旧商品主图
            LambdaQueryWrapper<AsCommodityImgEntity> queryImagePathsWrapper = new LambdaQueryWrapper<>();
            queryImagePathsWrapper.eq(AsCommodityImgEntity::getCommodityId, asCommodityEntity.getId());
            asCommodityImgHService.remove(queryImagePathsWrapper);

            // 获取商品主图
            List<String> imagePaths = asCommodityInfoDto.getImagePaths();
            if (imagePaths != null && !imagePaths.isEmpty()) {
                // 批量更新商品主图
                List<AsCommodityImgEntity> asCommodityImgEntityList = imagePaths.stream()
                    .map(imagePath -> {
                        AsCommodityImgEntity asCommodityImgEntity = new AsCommodityImgEntity();
                        asCommodityImgEntity.setCommodityId(asCommodityEntity.getId());
                        asCommodityImgEntity.setUrl(imagePath);
                        return asCommodityImgEntity;
                    }).collect(Collectors.toList());
                asCommodityImgHService.saveBatch(asCommodityImgEntityList);
            }
        }

        if (Objects.nonNull(asCommodityInfoDto.getImages())) {// 删除旧的商品描述图
            LambdaQueryWrapper<AsCommodityDescribeImgEntity> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(AsCommodityDescribeImgEntity::getCommodityId, asCommodityEntity.getId());
            asCommodityDescribeImgHService.remove(queryWrapper);

            // 获取新的商品描述图
            List<String> images = asCommodityInfoDto.getImages();
            if (images != null && !images.isEmpty()) {
                // 批量添加新的商品描述图
                List<AsCommodityDescribeImgEntity> asCommodityDescribeImgEntityList = images.stream().map(image -> {
                    AsCommodityDescribeImgEntity asCommodityDescribeImgEntity = new AsCommodityDescribeImgEntity();
                    asCommodityDescribeImgEntity.setCommodityId(asCommodityEntity.getId());
                    asCommodityDescribeImgEntity.setDescribeImage(image);
                    return asCommodityDescribeImgEntity;
                }).collect(Collectors.toList());
                asCommodityDescribeImgHService.saveBatch(asCommodityDescribeImgEntityList);
            }
        }

    }

    @Override
    public AsCommodityInfoVo getCommodityById(Long id) {
        // 查询商品基本信息
        AsCommodityEntity asCommodityEntity = asCommodityHMapper.selectById(id);
        if (asCommodityEntity == null) {
            return null; // 如果商品不存在，返回 null 或者抛出异常
        }

        // 将商品信息拷贝到 AsCommodityInfoVo
        AsCommodityInfoVo asCommodityInfoVo = BeanUtil.copyProperties(asCommodityEntity, AsCommodityInfoVo.class);

        // 查询商品主图
        List<AsCommodityImgEntity> asCommodityImgEntityList = asCommodityImgHService.list(
            new LambdaQueryWrapper<AsCommodityImgEntity>().eq(AsCommodityImgEntity::getCommodityId, id)
        );

        // 将主图 URL 存入 imagePaths 集合
        List<String> imagePaths = asCommodityImgEntityList.stream()
            .map(AsCommodityImgEntity::getUrl)  // 获取 URL 属性
            .collect(Collectors.toList());

        // 查询商品描述图
        List<AsCommodityDescribeImgEntity> asCommodityDescribeImgEntityList = asCommodityDescribeImgHService.list(
            new LambdaQueryWrapper<AsCommodityDescribeImgEntity>().eq(AsCommodityDescribeImgEntity::getCommodityId, id)
        );

        // 将描述图 URL 存入 images 集合
        List<String> images = asCommodityDescribeImgEntityList.stream()
            .map(AsCommodityDescribeImgEntity::getDescribeImage)  // 获取描述图 URL 属性
            .collect(Collectors.toList());

        //查询店家信息
        SysUserEntity sysUserEntity = sysUserMapper.selectById(asCommodityEntity.getUserId());


        // 将图片信息存入 AsCommodityInfoVo
        asCommodityInfoVo.setImagePaths(imagePaths);
        asCommodityInfoVo.setImages(images);
        asCommodityInfoVo.setUser_name(sysUserEntity.getUserName());
        asCommodityInfoVo.setAvatar(sysUserEntity.getAvatar());
        asCommodityInfoVo.setRemark(sysUserEntity.getRemark());

        return asCommodityInfoVo;
    }

    @Override
    public Object selCommodity(AsCommodityEntity asCommodityEntity, Pageable pageable) {
        // 创建分页对象
        Page<AsCommodityEntity> page = new Page<>(pageable.getPageNumber() + 1, pageable.getPageSize());

        // 构建查询条件
        LambdaQueryWrapper<AsCommodityEntity> queryWrapper = new LambdaQueryWrapper<>();

        // 仅在条件存在时才添加模糊查询
        if (asCommodityEntity.getTradeName() != null && !asCommodityEntity.getTradeName().trim().isEmpty()) {
            queryWrapper.like(AsCommodityEntity::getTradeName, asCommodityEntity.getTradeName());
        }

        // 执行查询并分页
        Page<AsCommodityEntity> resultPage = asCommodityHMapper.selectPage(page, queryWrapper);

        // 获取查询结果中的商品 ID 列表
        List<Long> commodityIds = resultPage.getRecords().stream()
            .map(AsCommodityEntity::getId)
            .collect(Collectors.toList());

        // 如果没有商品 ID，则返回空结果
        if (commodityIds.isEmpty()) {
            Page<AsCommodityInfoVo> emptyPage = new Page<>(pageable.getPageNumber() + 1, pageable.getPageSize());
            emptyPage.setTotal(resultPage.getTotal());
            return emptyPage;
        }

        // 查询商品主图
        List<AsCommodityImgEntity> asCommodityImgEntityList = asCommodityImgHService.list(
            new LambdaQueryWrapper<AsCommodityImgEntity>().in(AsCommodityImgEntity::getCommodityId, commodityIds)
        );

        // 查询商品描述图
        List<AsCommodityDescribeImgEntity> asCommodityDescribeImgEntityList = asCommodityDescribeImgHService.list(
            new LambdaQueryWrapper<AsCommodityDescribeImgEntity>().in(AsCommodityDescribeImgEntity::getCommodityId, commodityIds)
        );

        // 将主图和描述图按商品 ID 分类
        Map<Long, List<String>> mainImgMap = asCommodityImgEntityList.stream()
            .collect(Collectors.groupingBy(
                AsCommodityImgEntity::getCommodityId,
                Collectors.mapping(AsCommodityImgEntity::getUrl, Collectors.toList())
            ));

        Map<Long, List<String>> describeImgMap = asCommodityDescribeImgEntityList.stream()
            .collect(Collectors.groupingBy(
                AsCommodityDescribeImgEntity::getCommodityId,
                Collectors.mapping(AsCommodityDescribeImgEntity::getDescribeImage, Collectors.toList())
            ));

        // 转换查询结果为 AsCommodityInfoVo
        List<AsCommodityInfoVo> voList = resultPage.getRecords().stream()
            .map(entity -> {
                AsCommodityInfoVo vo = BeanUtil.copyProperties(entity, AsCommodityInfoVo.class);
                vo.setImagePaths(mainImgMap.get(entity.getId())); // 设置主图
                vo.setImages(describeImgMap.get(entity.getId()));  // 设置描述图
                return vo;
            })
            .collect(Collectors.toList());

        // 创建新的分页对象，并设置查询结果
        Page<AsCommodityInfoVo> resultVoPage = new Page<>(pageable.getPageNumber() + 1, pageable.getPageSize());
        resultVoPage.setRecords(voList);
        resultVoPage.setTotal(resultPage.getTotal());

        return resultVoPage;
    }

}


